package com.elite.groovy.callback


import com.elite.groovy.util.EliteBean
import cn.com.elite.PropertiesUtil
import com.elite.groovy.util.Util
import cn.com.kh.HttpClientProxy
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray

import com.wisdge.utils.StringUtils
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.util.Base64Utils
import org.springframework.util.DigestUtils
import net.sf.json.JSONObject;
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiTdxPushList*
 * @Description:泰迪熊 名单推送*
 * @remak ：推送给泰迪熊名单接口*
 * @author: TH*
 * @date 2023-02-06 11:11:00
 *
 */
public class apiTPRJPushList implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiTPRJPushList.class);
    public static long TimeMillis = System.currentTimeMillis();
    /**
     * 编码
     */
    private static final String ENCODING = "UTF-8";
    /**
     * 算法定义
     */
    private static final String AES_ALGORITHM = "AES";
    /**
     * 指定填充方式
     */
    private static final String CIPHER_PADDING = "AES/ECB/PKCS5Padding";


    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        JSONObject result = new JSONObject();
        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());


        try {
            String selectSQL = '''
                        Select ob.objective_Guid,
                        s.staff_id,
                        c.Customername || ',' || ob.objective_Guid,
                        case
                          when c.Mobile is not null then
                           c.Mobile
                          when c.tel_1 is not null then
                           c.tel_1
                          when c.atel_1 is not null then
                           c.atel_1
                          when c.atel_2 is not null then
                           c.atel_2
                          when c.atel_3 is not null then
                           c.atel_3
                          when c.Atel_4 is not null then
                           c.atel_4
                        end as mobile,
                        s.staffname,
                        s.stringfield4,
                        s.stringfield5,
                        s.stringfield6,
                        ob.handlegroup_id,
                        case
                          when ob.attempt = 0 then
                           '首拨任务'
                          when ob.expectstarttime is not null and ob.attempt != 0 then
                           '预约任务'
                        end as taskname,
                        to_char(sysdate, 'yyyymmdd') as datetime,
                        o.custlistname,
                        c.customername
                   From elitetask ob
                   Left Join Customer T2
                     On ob.Customer_Guid = T2.Customer_Guid
                   Left Join Customer c
                     On c.Customer_Guid = T2.Parent_Guid
                   Left Join objective o
                    on o.objective_Guid=ob.objective_Guid
                   Left Join staff s
                     On s.staff_id = ob.handleby_id
                   Left Join rolegroup r
                     On r.rolegroup_id = ob.handlegroup_id
                  Where ob.obflag = 1
                    and ob.handleby_id is not null
                    and s.stringfield3 = '1'
                    And ob.Createddate > Add_Months(Sysdate, -6)
                   AND  o.STRINGFIELD4 is not null 
                   and o.STRINGFIELD4 >=to_date(to_char(sysdate,'YYYY-MM-DD')||'00:00:00','yyyy-mm-dd hh24:mi:ss')
                   and o.STRINGFIELD4 <=to_date(to_char(sysdate,'YYYY-MM-DD')||'23:59:59','yyyy-mm-dd hh24:mi:ss') 
                   AND o.STRINGFIELD5 ='ZJTDX'
                   and c.Mobile is not null
                   and   c.Customername is not null 
                   AND  NOT EXISTS(
                   select tdx.OBJECTIVE_GUID from TDX_PUSH_LIST tdx
                   where tdx.OBJECTIVE_GUID=o.OBJECTIVE_GUID
                   and tdx.CREATEDDATE >=to_date(to_char(sysdate,'YYYY-MM-DD')||'00:00:00','yyyy-mm-dd hh24:mi:ss')
                   and tdx.CREATEDDATE <=to_date(to_char(sysdate,'YYYY-MM-DD')||'23:59:59','yyyy-mm-dd hh24:mi:ss') 
                   )        and rownum<=?
                        ''';
            List<Map<String, Object>> selectExits = jt.queryForList(selectSQL,KHDBConfig.getParam(eliteBean,"TDXNUM",""));
            String name = "";





            String str = String.valueOf(TimeMillis);
            String IV_SEED = DigestUtils.md5DigestAsHex(str.getBytes());
            String resu;
            if (selectExits.size() > 0) {
                for (int i=0; i < selectExits.size(); i++) {
                    Map selectExitsm = selectExits.get(i);
                    String datetime = selectExitsm.get("datetime");
                    String taskname = selectExitsm.get("taskname");
                    String staffname = selectExitsm.get("staffname");
                    String workgroupJid = selectExitsm.get("stringfield4");
                    String agentJid = selectExitsm.get("stringfield6");
                    String staff_id = selectExitsm.get("staff_id");
                    String handlegroup_id = selectExitsm.get("handlegroup_id");

                    //拼接名字
                   String ffname= datetime.toString() + taskname.toString() + staffname.toString();
                    String cxsql=''' 
                                  Select taskid,TASKNAME from  TDX_PUSH_LIST tdx where 1=1
                                   and tdx.TASKNAME=?
                                   and tdx.CREATEDDATE >=to_date(to_char(sysdate,'YYYY-MM-DD')||'00:00:00','yyyy-mm-dd hh24:mi:ss')
                                   and tdx.CREATEDDATE <=to_date(to_char(sysdate,'YYYY-MM-DD')||'23:59:59','yyyy-mm-dd hh24:mi:ss') 
                                   AND ROWNUM<=1
                                  ''';
                    List<Map<String, Object>> cxselect  = jt.queryForList(cxsql,ffname);

                    //判断任务名称是否存在,存在则追加，不存在则新建
                    if (cxselect.size()>0){
                        log.debug("开始执行追加");
                        String taskid=cxselect.get(0).get("taskid");

                        resu = push_append(eliteBean,jt,selectExitsm,taskid,ffname);

                    }else{
                        log.debug("开始执行创建");
                        resu = push_create(eliteBean, staffname, datetime, taskname, workgroupJid, jt, selectExitsm, IV_SEED,agentJid);
                    }


                }

               JSONObject jbm=JSONObject.fromObject(resu);
                log.debug("jb:"+jbm.toString());
                result.put("code",GetJV(jbm,"code"));
                result.put("msg", GetJV(jbm,"  "));
            } else {
                result.put("code", 1);
                result.put("msg", "无可推送名单");
            }




        } catch (Exception e) {
            log.error("接口处理异常", e);
            result.put("code", -1);
            result.put("msg", e.getMessage());
            result.put("data", "");
        }

        log.debug("推送名单处理完成返回结果:" + result.toString());

        return result.toString();
    }
    /**
     * 创建任务
     * @param eliteBean
     * @param staffname
     * @param datetime
     * @param taskname
     * @param workgroupJid
     * @param jt
     * @param selectExitsm
     * @param IV_SEED
     * @param agentJid
     * @return
     */
    public static String  push_create(EliteBean eliteBean, String staffname, String datetime, String taskname, String workgroupJid, JdbcTemplate jt, Map selectExitsm, String IV_SEED,String agentJid) {
        String sql = "select WEBSERVICEURL From sysc_interface where WEBTYPE='ZJ_TDX'";
        List<Map<String, Object>> createlist = jt.queryForList(sql)
        JSONObject jb =new JSONObject();
        if (createlist.size() > 0) {
            Map createmap = createlist.get(0)
            String url = createmap.get("WEBSERVICEURL");
            PropertiesUtil cfg = new PropertiesUtil();
            String proxyIp = cfg.readValue("QingNiu.ProxyIP");
            String proxyPort = cfg.readValue("QingNiu.ProxyPort");

            JSONObject obj=new JSONObject();
            JSONObject createbody=new JSONObject();
            JSONArray agentJids = new JSONArray()
            JSONArray customers = new JSONArray();
            JSONObject obj2=new JSONObject();
            String sql2 = "select WEBSERVICEURL From sysc_interface where WEBTYPE='groovy'";
            List<Map<String, Object>> groovyUrl = jt.queryForList(sql2)
            String geturl=groovyUrl.get(0).get("WEBSERVICEURL");

            String tokenUrl=geturl.toString()+"apiTdxToken";

            //调用内部接口获取泰迪熊Token
             String tokenbody=Util.doHttpPost(tokenUrl,"","UTF-8", "20000" as int,0,"");

            JSONObject body = JSONObject.fromObject(tokenbody);
            if (body.getInt("code")==200){
                String token= KHUtil.GetJV(body as org.json.JSONObject,"token");
            //设置请求表头
            Map<String, String> TokenParams = new HashMap<String, String>();
            TokenParams.put("X-Token", token);
            TokenParams.put("Content-Type", "application/json");
                obj2.put("EXTEND1",selectExitsm.get("objective_Guid"));
                //obj.put("name", encrypt(selectExitsm.get("customername").toString(), IV_SEED.substring(8, 24)));
                // obj.put("phone", encrypt(selectExitsm.get("mobile").toString(), IV_SEED.substring(8, 24)));
                obj.put("name", selectExitsm.get("customername").toString());
                obj.put("phone", selectExitsm.get("mobile").toString());
                obj.put("extendFields",obj2)
                /**
                if (agentJids.indexOf(staffname) == -1) {
                    agentJids.add(staffname);
                }
                 **/

               // agentJids.add(agentJid);

                customers.add(obj);
                createbody.put("name", datetime + taskname + staffname);//任务名称
                createbody.put("description", "太平财险网电销自动任务");//备注
                createbody.put("businessId",KHDBConfig.getParam(eliteBean, "TDXRW", ""));//泰迪熊任务类型
                createbody.put("accessNumber",KHDBConfig.getParam(eliteBean, "TDXJRH", ""));//接入号
                createbody.put("sceneId", KHDBConfig.getParam(eliteBean, "TDXCID", ""));//场景ID
                createbody.put("workgroupJid", workgroupJid); //人机耦合技能组
                createbody.put("agentJid", agentJid);//指定人
                createbody.put("agentJids",[KHDBConfig.getParam(eliteBean, "TDXJID", "")]);//指定人
                createbody.put("customers", customers);//客户信息List
                log.debug("【泰迪熊创建任务】接口请求参数：" + createbody.toString());

                String orgName = KHDBConfig.getParam(eliteBean, "TDXQID", "");//orgName	企业id
                String appName = KHDBConfig.getParam(eliteBean, "TDXAID", "");//appName	appId

                String createUrl = url.toString() + "/rest/" + orgName.toString() + "/" + appName.toString() + "/cc/mmcTask/create";//请求URL拼接

                log.debug("【泰迪熊创建任务】接口请求URL：" + createUrl.toString());


                String create_result = Util.doHttpPostUseHead1(createUrl, createbody.toString(), "UTF-8", 200000, 0, TokenParams,"",proxyIp, proxyPort as int,true);

                 jb=JSONObject.fromObject(create_result);

                log.debug("【泰迪熊创建任务】接口返回参数：" + jb.toString());
                     //123
                    //String sql1 = "insert into qt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values(sys_guid()," + jb.getString("taskId") + ",'泰迪熊创建任务'," + createbody.toString() + "," + jb.toString() + ",sysdate,sysdate)"
                   //jt.update(sql1);
                  //String s = selectExitsm.get("customername").toString();
                 //int c = s.indexOf(",");
                //String objective_guid = s.substring(c + 1, s.length());
               //String customername = s.substring(0, c);



                if (jb.getInt("code") ==200) {
                    String pushlisthis = ''' 
                                          insert 
                                          into 
                                          TDX_PUSH_LIST
                                          (
                                          REC_GUID,
                                          CREATEDDATE,
                                          TASKID,
                                          TASKNAME,
                                          CUSTOMERNAME,
                                          MOBILE,
                                          STAFF_ID,
                                          QUEUE,
                                          OBJECTIVE_GUID,
                                          custlistname,
                                          rolegroup_id,
                                          remark
                                          ) 
                                          values
                                          (
                                          sys_guid(),
                                          sysdate,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           '自动任务推送'
                                            )
                                            ''';

                    jt.update(
                            pushlisthis,
                            GetJV(jb,"taskId"),
                            datetime.toString() + taskname.toString() + staffname.toString(),
                            selectExitsm.get('customername'),
                            selectExitsm.get('mobile'),
                            selectExitsm.get("staff_id"),
                            selectExitsm.get("stringfield4"),
                            selectExitsm.get("objective_guid"),
                            selectExitsm.get("custlistname"),
                            selectExitsm.get("handlegroup_id")
                             );
                } else {
                    String pushlist = '''
                         insert 
                         into
                         TDX_PUSH_LIST_HIS
                         (REC_GUID,
                         CREATEDDATE,
                         TASKID,
                         TASKNAME,
                         CUSTOMERNAME,
                         MOBILE,
                         STAFF_ID,
                         QUEUE,
                         OBJECTIVE_GUID,
                         custlistname,
                         rolegroup_id,
                          remark
                         ) 
                        values
                        (
                        sys_guid(),
                        sysdate,
                          ?,
                          ?,
                          ?,
                          ?,
                          ?,
                          ?,
                          ?,
                          ?,
                          ?,
                          '自动任务推送'
                          )
                          ''';

                    jt.update(
                            pushlist,
                            GetJV(jb,"taskId"),
                            datetime.toString() + taskname.toString() + staffname.toString(),
                            selectExitsm.get('customername') ,
                            selectExitsm.get("mobile"),
                            selectExitsm.get("staff_id"),
                            selectExitsm.get("stringfield4"),
                            selectExitsm.get("objective_guid"),
                            selectExitsm.get("custlistname"),
                            selectExitsm.get("handlegroup_id")
                             );
                }
            }else{
             log.error("获取泰迪熊Token异常："+body.toString());
            }


        }
       return jb.toString() ;
    }
    /**
     * 追加任务
     * @param eliteBean
     * @param jt
     * @param selectExitsm
     * @param taskid
     * @param taskname
     * @return
     */
    public static String   push_append(EliteBean eliteBean,JdbcTemplate jt,Map selectExitsm,String taskid,String taskname) {
        String sql = "select WEBSERVICEURL From sysc_interface where WEBTYPE='ZJ_TDX'";
        List<Map<String, Object>> createlist = jt.queryForList(sql)
        JSONObject jb = new JSONObject();
        JSONObject obj2=new JSONObject();
        if (createlist.size() > 0) {
            Map createmap = createlist.get(0)
            String url = createmap.get("WEBSERVICEURL");
            PropertiesUtil cfg = new PropertiesUtil();
            String proxyIp = cfg.readValue("QingNiu.ProxyIP");
            String proxyPort = cfg.readValue("QingNiu.ProxyPort");

            JSONObject obj = new JSONObject();
            JSONArray agentJids = new JSONArray()
            JSONArray customers = new JSONArray();

            String sql2 = "select WEBSERVICEURL From sysc_interface where WEBTYPE='groovy'";
            List<Map<String, Object>> groovyUrl = jt.queryForList(sql2)
            String geturl = groovyUrl.get(0).get("WEBSERVICEURL");

            String tokenUrl = geturl.toString() + "apiTdxToken";

            //调用内部接口获取泰迪熊Token
            String tokenbody = Util.doHttpPost(tokenUrl, "", "UTF-8", "200000" as int, 0, "");

            JSONObject body = JSONObject.fromObject(tokenbody);
            if (body.getInt("code") == 200) {
                String token = GetJV(body, "token");
                //设置请求表头
                Map<String, String> TokenParams = new HashMap<String, String>();
                TokenParams.put("X-Token", token);
                TokenParams.put("Content-Type", "application/json");
                String orgName = KHDBConfig.getParam(eliteBean, "TDXQID", "");//orgName	企业id
                String appName = KHDBConfig.getParam(eliteBean, "TDXAID", "");//appName	appId

                String createUrl = url.toString() + "/rest/" + orgName.toString() + "/" + appName.toString() + "/cc/mmcTask/append";//请求URL拼接

                JSONObject obJson =new JSONObject();
                JSONObject toJson=new JSONObject();
                JSONArray arr =new JSONArray();
                obJson.put("name",selectExitsm.get("customername").toString());
                obJson.put("phone",selectExitsm.get("mobile").toString());
                obj2.put("EXTEND1",selectExitsm.get("objective_Guid"));
                obJson.put("extendFields",obj2)
                arr.add(obJson);

                toJson.put("taskId",taskid);
                toJson.put("customers",arr);

                log.debug("【泰迪熊追加任务】接口请求URL：" + createUrl.toString());
                log.debug("【泰迪熊请求追加任务】接口请求参数：" + toJson.toString());
                String create_result = Util.doHttpPostUseHead1(createUrl, toJson.toString(), "UTF-8", 200000, 0, TokenParams,"",proxyIp, proxyPort as int,true);

                jb=JSONObject.fromObject(create_result);

                log.debug("【泰迪熊追加】接口返回参数：" + jb.toString());


                if (jb.getInt("code") ==200) {
                    String pushlisthis = ''' 
                                          insert 
                                          into 
                                          TDX_PUSH_LIST
                                          (
                                          REC_GUID,
                                          CREATEDDATE,
                                          TASKID,
                                          TASKNAME,
                                          CUSTOMERNAME,
                                          MOBILE,
                                          STAFF_ID,
                                          QUEUE,
                                          OBJECTIVE_GUID,
                                          custlistname,
                                          rolegroup_id,
                                          remark
                                          ) 
                                          values
                                          (
                                          sys_guid(),
                                          sysdate,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           '自动任务推送'
                                            )
                                            ''';

                    jt.update(
                            pushlisthis,
                            taskid,
                            taskname,
                            selectExitsm.get('customername'),
                            selectExitsm.get('mobile'),
                            selectExitsm.get("staff_id"),
                            selectExitsm.get("stringfield4"),
                            selectExitsm.get("objective_guid"),
                            selectExitsm.get("custlistname"),
                            selectExitsm.get("handlegroup_id")
                    );
                } else {
                    String pushlist = '''
                         insert 
                         into
                         TDX_PUSH_LIST_HIS
                         (REC_GUID,
                         CREATEDDATE,
                         TASKID,
                         TASKNAME,
                         CUSTOMERNAME,
                         MOBILE,
                         STAFF_ID,
                         QUEUE,
                         OBJECTIVE_GUID,
                         custlistname,
                         rolegroup_id,
                          remark
                         ) 
                        values
                        (
                        sys_guid(),
                        sysdate,
                          ?,
                          ?,
                          ?,
                          ?,
                          ?,
                          ?,
                          ?,
                          ?,
                          ?,
                          '自动任务推送'
                          )
                          ''';

                    jt.update(
                            pushlist,
                            taskid,
                            taskname,
                            selectExitsm.get('customername') ,
                            selectExitsm.get("mobile"),
                            selectExitsm.get("staff_id"),
                            selectExitsm.get("stringfield4"),
                            selectExitsm.get("objective_guid"),
                            selectExitsm.get("custlistname"),
                            selectExitsm.get("handlegroup_id")
                    );
                }




            }else{
                log.error("获取泰迪熊Token异常："+body.toString());
            }

        }


        return jb.toString();
    }


    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
                //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }


}
